package com.bdsy.system.shiro;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.bdsy.system.model.User;

public class ShiroUtils {

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static User getUser() {
		return (User)SecurityUtils.getSubject().getPrincipal();
	}

	public static String getUserId() {
		return getUser().getUserId();
	}
	
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin(String loginName) {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}
	
	public static String getKaptcha(String key) {
		String kaptcha = getSessionAttribute(key).toString();
		getSession().removeAttribute(key);
		return kaptcha;
	}

	/**
	 * 判断是不是ajax请求
	 * 
	 * @param request
	 * @return
	 * @author 
	 */
	public static boolean isAjax(HttpServletRequest request) {
		String xHeader = request.getHeader("X-Requested-With");
		if (xHeader != null && xHeader.contains("XMLHttpRequest")) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是不是app请求
	 * 
	 * @param request
	 * @return
	 * @author
	 */
	public static boolean isApp(HttpServletRequest request) {
		if(request.getRequestURL().toString().contains("/app/")){
			return true;
		}
		String s1 = request.getHeader("user-agent");
		if (s1.contains("Android")) {
			return true;
		} else if (s1.contains("iPhone")) {
			return true;
		} else if (s1.contains("iPad")) {
			
		} else {
			
		}
		return false;
	}
}
